# root CMakeLists for the LaundredSheep project
project(LaundredSheep)
set(PROJECT_VERSION "0.0.1")

cmake_minimum_required(VERSION 2.8.4)
if(NOT (CMAKE_MAJOR_VERSION VERSION_LESS 3))
  cmake_policy(SET CMP0043 OLD)
endif()

set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${PROJECT_SOURCE_DIR}/cmake")

include(BuildTypeLSRelease)
if (NOT CMAKE_BUILD_TYPE)
    message(STATUS "No build type selected, default to LSRelease")
    set(CMAKE_BUILD_TYPE "LSRelease")
endif()

option(CHECK_ASSETS "Check if assets are installed in ../ls-assets" ON)



if(UNIX AND NOT APPLE)
    option(USE_XRANDR "Use xrandr instead of vidmode" ON)
    option(USE_ASAN   "Build with Leak/Address sanitizer" OFF)
endif()

set(LS_SOURCE_DIR "src")
set(LS_DATA_DIR "${PROJECT_SOURCE_DIR}/data")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${PROJECT_BINARY_DIR}/bin")

# Define install paths
set(LS_INSTALL_BINARY_DIR "bin" CACHE
    STRING "Install executable to this directory, absolute or relative to CMAKE_INSTALL_PREFIX")
set(LS_INSTALL_DATA_DIR "share/laundredsheep" CACHE
    STRING "Install data folder to this directory, absolute or relative to CMAKE_INSTALL_PREFIX")

# These variables enable MSVC to find libraries located in "dependencies"
if(WIN32)
    set(ENV{PATH} "$ENV{PATH};${PROJECT_SOURCE_DIR}/dependencies/include")
    set(ENV{LIB} ${PROJECT_SOURCE_DIR}/dependencies/lib)
    set(ENV{OPENALDIR} ${PROJECT_SOURCE_DIR}/dependencies)
    add_definitions(-D_IRR_STATIC_LIB_)
endif()



# Build glew library
add_subdirectory("${PROJECT_SOURCE_DIR}/lib/glew")
include_directories("${PROJECT_SOURCE_DIR}/lib/glew/include")

if((WIN32 AND NOT MINGW) OR APPLE)
    if (NOT APPLE)
    # Build zlib library
    add_subdirectory("${PROJECT_SOURCE_DIR}/lib/zlib")
    include_directories("${PROJECT_SOURCE_DIR}/lib/zlib")

    set(ZLIB_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/lib/zlib" "${PROJECT_BINARY_DIR}/lib/zlib/")
    set(ZLIB_LIBRARY zlibstatic)
    endif()

    # Build png library
    set (SKIP_INSTALL_ALL TRUE)
    set (PNG_STATIC TRUE)
    set (PNG_TESTS FALSE)
    set (PNG_SHARED FALSE)
    add_subdirectory("${PROJECT_SOURCE_DIR}/lib/libpng")
    include_directories("${PROJECT_SOURCE_DIR}/lib/libpng")

    #build jpeg library
    add_subdirectory("${PROJECT_SOURCE_DIR}/lib/jpeglib")
    include_directories("${PROJECT_SOURCE_DIR}/lib/jpeglib")

    set(PNG_PNG_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/lib/libpng/")
    set(PNG_LIBRARY png15_static)
    set(JPEG_INCLUDE_DIR "${PROJECT_SOURCE_DIR}/lib/jpeglib/")
    set(JPEG_LIBRARY jpeglib)
endif()
# Build the irrlicht library
add_subdirectory("${PROJECT_SOURCE_DIR}/lib/irrlicht")
include_directories("${PROJECT_SOURCE_DIR}/lib/irrlicht/include")


# Set include paths
include_directories(${LS_SOURCE_DIR})

if(APPLE)
    set(CMAKE_C_FLAGS "${CMAKE_C_FLAGS} -arch i386")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -arch i386 -F/Library/Frameworks")
elseif(MSVC)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} /MP")   # Enable multi-processor compilation (faster)
endif()


# OpenMP
find_package(OpenMP)
if (OPENMP_FOUND)
    set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
    set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif()

# OpenGL
find_package(OpenGL REQUIRED)
include_directories(${OPENGL_INCLUDE_DIR})

if(UNIX AND NOT APPLE)
    find_package(X11 REQUIRED)
    include_directories(${X11_INCLUDE_DIR})

    if(USE_XRANDR)
        find_package(Xrandr REQUIRED)
        if(NOT XRANDR_FOUND)
            message(FATAL_ERROR "XRANDR not found.")
        endif()
    else()
        find_library(IRRLICHT_XF86VM_LIBRARY Xxf86vm)
        mark_as_advanced(IRRLICHT_XF86VM_LIBRARY)
    endif()
endif()

# Set some compiler options
if(UNIX OR MINGW)
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++0x")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -Wall")
endif()

if(MINGW AND CMAKE_BUILD_TYPE MATCHES Release)
    SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wl,--subsystem,windows")
endif()

if(WIN32)
    # By default windows.h has macros defined for min and max that screw up everything
    add_definitions(-DNOMINMAX)

    # And shut up about unsafe stuff
    add_definitions(-D_CRT_SECURE_NO_WARNINGS)
endif()

if(MSVC)
    # VS will automatically add NDEBUG for release mode, but only _DEBUG in debug mode.
    # Since LS uses DEBUG, this is added for debug compilation only:
    set_property(DIRECTORY PROPERTY COMPILE_DEFINITIONS_DEBUG DEBUG)
else()
    # All non VS generators used create only a single compile mode, so
    # compile flags can be simplye be added
    if(CMAKE_BUILD_TYPE MATCHES Debug)
        add_definitions(-DDEBUG)
    else()
        add_definitions(-DNDEBUG)
    endif()
endif()

# TODO: remove this switch
add_definitions(-DHAVE_OGGVORBIS)

#if(WIN32)
#    configure_file("${LS_SOURCE_DIR}/windows_installer/icon_rc.template" "${PROJECT_BINARY_DIR}/tmp/icon.rc")
#endif()

# Provides list of source and header files (LS_SOURCES and LS_HEADERS)
include(sources.cmake)

# Generate source groups useful for MSVC project explorer
include(cmake/SourceGroupFunctions.cmake)
source_group_hierarchy(LS_SOURCES LS_HEADERS)


if(APPLE)
    # icon files to copy in the bundle
    set(OSX_ICON_FILES ${PROJECT_SOURCE_DIR}/data/laundredsheep.icns)
    set_source_files_properties(${OSX_ICON_FILES} PROPERTIES MACOSX_PACKAGE_LOCATION Resources)
    set(LS_SOURCES ${LS_SOURCES} ${OSX_ICON_FILES})

    # build the executable and create an app bundle
    add_executable(laundredsheep MACOSX_BUNDLE ${LS_SOURCES})

    find_library(IOKIT_LIBRARY IOKit)
    find_library(QUICKTIME_LIBRARY QuickTime)
    find_library(CARBON_LIBRARY Carbon)
    find_library(AUDIOUNIT_LIBRARY AudioUnit)
    find_library(COCOA_LIBRARY Cocoa)

    target_link_libraries(laundredsheep
         ${IOKIT_LIBRARY}
         ${QUICKTIME_LIBRARY}
         ${CARBON_LIBRARY}
         ${AUDIOUNIT_LIBRARY}
         ${COCOA_LIBRARY})

    # configure CMake to use a custom Info.plist
    set_target_properties(laundredsheep PROPERTIES
        MACOSX_BUNDLE_INFO_PLIST ${PROJECT_SOURCE_DIR}/data/LaundredSheep-Info.plist)

    if(CMAKE_GENERATOR MATCHES "Xcode")
        add_custom_command(TARGET laundredsheep POST_BUILD
            COMMAND ln -f -s ${PROJECT_SOURCE_DIR}/data ${CMAKE_BINARY_DIR}/bin/\${CONFIGURATION}/laundredsheep.app/Contents/Resources)
    else()
        add_custom_command(TARGET laundredsheep POST_BUILD
            COMMAND ln -f -s ${PROJECT_SOURCE_DIR}/data ${CMAKE_BINARY_DIR}/bin/laundredsheep.app/Contents/Resources)
    endif()
else()
    if(MSVC)
        set(PTHREAD_NAMES pthreadVC2)
    elseif(MINGW)
        set(PTHREAD_NAMES "winpthread-1" "libwinpthread-1" "pthreadGC2")
    endif()
    find_library(PTHREAD_LIBRARY NAMES pthread ${PTHREAD_NAMES} PATHS ${PROJECT_SOURCE_DIR}/dependencies/lib)
    mark_as_advanced(PTHREAD_LIBRARY)

    # Set data dir (absolute or relative to CMAKE_INSTALL_PREFIX)
    if(NOT LS_INSTALL_DATA_DIR_ABSOLUTE)
        get_filename_component(LS_INSTALL_DATA_DIR_ABSOLUTE ${LS_INSTALL_DATA_DIR} ABSOLUTE)
        if(${LS_INSTALL_DATA_DIR_ABSOLUTE} STREQUAL ${LS_INSTALL_DATA_DIR})
            add_definitions(-DLAUNDREDSHEEP_DATADIR=\"${LS_INSTALL_DATA_DIR_ABSOLUTE}\")
        else()
            add_definitions(-DLAUNDREDSHEEP_DATADIR=\"${CMAKE_INSTALL_PREFIX}/${LS_INSTALL_DATA_DIR}\")
        endif()
    else()
        add_definitions(-DLAUNDREDSHEEP_DATADIR=\"${LS_INSTALL_DATA_DIR_ABSOLUTE}\")
    endif()

    # Build the final executable
    add_executable(laundredsheep ${LS_SOURCES} ${LS_RESOURCES} ${LS_HEADERS})
    target_link_libraries(laundredsheep ${PTHREAD_LIBRARY})
endif()

# CURL
if(WIN32)
    target_link_libraries(laundredsheep ${PROJECT_SOURCE_DIR}/dependencies/lib/libcurldll.a)
else()
    find_package(CURL REQUIRED)
    include_directories(${CURL_INCLUDE_DIRS})
endif()

# Common library dependencies
target_link_libraries(laundredsheep
    glew
    lsirrlicht
    ${CURL_LIBRARIES}
    ${OGGVORBIS_LIBRARIES}
    ${OPENAL_LIBRARY}
    ${OPENGL_LIBRARIES}
    )

if(UNIX AND NOT APPLE)
    target_link_libraries(laundredsheep ${X11_LIBRARIES})
    if(USE_XRANDR)
        target_link_libraries(laundredsheep ${XRANDR_LIBRARIES})
    else()
        target_link_libraries(laundredsheep ${IRRLICHT_XF86VM_LIBRARY})
    endif()
    if(USE_ASAN)
        set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=address -fno-omit-frame-pointer")
        target_link_libraries(laundredsheep "-fsanitize=address")
    endif()
endif()

if(APPLE)
    # In theory it would be cleaner to let CMake detect the right dependencies. In practice, this means that if a OSX user has
    # unix-style installs of Vorbis/Ogg/OpenAL/etc. they will be picked up over our frameworks. This is blocking when I make releases :
    # the mac I use to make LS releases does have other installs of vorbis/ogg/etc. which aren't compatible with LS, so letting
    # CMake pick the library it wants essentially means I can't build.
    set_target_properties(laundredsheep PROPERTIES LINK_FLAGS "-arch i386 -F/Library/Frameworks -framework OpenAL -framework Ogg -framework Vorbis")
    set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -I/Library/Frameworks/OpenAL.framework/Versions/A/Headers")
endif()



if(MSVC OR MINGW)
  target_link_libraries(laundredsheep iphlpapi.lib)
  add_custom_command(TARGET laundredsheep POST_BUILD
    COMMAND ${CMAKE_COMMAND} -E copy_directory
        "${PROJECT_SOURCE_DIR}/dependencies/dll"
        $<TARGET_FILE_DIR:laundredsheep>)
  add_custom_target(lsshaders SOURCES ${LS_SHADERS})
endif()

if(MINGW)
    find_library(LIBGCC NAMES "libgcc_s_dw2-1.dll" "libgcc_s_sjlj-1.dll" PATHS ${CMAKE_FIND_ROOT_PATH})
    if(LIBGCC)
        file(COPY ${LIBGCC} DESTINATION ${CMAKE_BINARY_DIR}/bin/)
    endif()
    find_library(LIBSTDCPP NAMES "libstdc++-6.dll" PATHS ${CMAKE_FIND_ROOT_PATH})
    if(LIBSTDCPP)
        file(COPY ${LIBSTDCPP} DESTINATION ${CMAKE_BINARY_DIR}/bin/)
    endif()
    find_library(LIBOPENMP NAMES "libgomp-1.dll" PATHS ${CMAKE_FIND_ROOT_PATH})
    if(LIBOPENMP)
        file(COPY ${LIBOPENMP} DESTINATION ${CMAKE_BINARY_DIR}/bin/)
    endif()
    find_library(LIBPTHREAD NAMES "winpthread-1.dll" "libwinpthread-1.dll" "pthreadGC2.dll" PATHS ${CMAKE_FIND_ROOT_PATH})
    if(LIBPTHREAD)
        file(COPY ${LIBPTHREAD} DESTINATION ${CMAKE_BINARY_DIR}/bin/)
    endif()
endif()

# Optional tools
#add_subdirectory(tools/font_tool)


# ==== Make dist target ====
if(MSVC OR MINGW)
  # Don't create a dist target for VS
else()
  add_custom_target(dist
    COMMAND rm -rf ${CMAKE_BINARY_DIR}/LaundredSheep-${PROJECT_VERSION} && rm -f ${CMAKE_BINARY_DIR}/LaundredSheep-${PROJECT_VERSION}.tar.bz2
            && echo "Exporting..."
            && svn export ${PROJECT_SOURCE_DIR} ${CMAKE_BINARY_DIR}/LaundredSheep-${PROJECT_VERSION}
            && echo "Compressing..."
            && cd ${CMAKE_BINARY_DIR}
            && tar -cjf ${CMAKE_BINARY_DIR}/LaundredSheep-${PROJECT_VERSION}.tar.bz2 ./LaundredSheep-${PROJECT_VERSION}
            && echo "Done, cleaning up"
            && rm -rf ${CMAKE_BINARY_DIR}/LaundredSheep-${PROJECT_VERSION}
    WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
  )
endif()


# ==== Checking if data folder exists ====
if(NOT IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/data)
  message( FATAL_ERROR "${CMAKE_CURRENT_SOURCE_DIR}/data folder doesn't exist" )
endif()

# ==== Checking if ls-assets folder exists ====
if(CHECK_ASSETS)
  if((IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/data/textures))
    message(STATUS "Assets found in data directory")
  elseif(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../ls-assets)
    set(LS_ASSETS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../ls-assets/)
    message(STATUS "Assets found")
  elseif(IS_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/../laundredsheep-assets)
    set(LS_ASSETS_DIR ${CMAKE_CURRENT_SOURCE_DIR}/../laundredsheep-assets/)
    message(STATUS "Assets found")
  else()
    set (CUR_DIR ${CMAKE_CURRENT_SOURCE_DIR})
    get_filename_component(PARENT_DIR ${CUR_DIR} PATH)
    message( FATAL_ERROR "${PARENT_DIR}/ls-assets folder doesn't exist. "
      "Please download the ls-assets, or disable this test with -DCHECK_ASSETS=off." )
  endif()
endif()


# ==== Install target ====
install(TARGETS laundredsheep RUNTIME DESTINATION ${LS_INSTALL_BINARY_DIR} BUNDLE DESTINATION .)
install(DIRECTORY ${LS_DATA_DIR} DESTINATION ${LS_INSTALL_DATA_DIR} PATTERN ".svn" EXCLUDE PATTERN ".git" EXCLUDE)
if(LS_ASSETS_DIR AND CHECK_ASSETS)
  install(DIRECTORY ${LS_ASSETS_DIR} DESTINATION ${LS_INSTALL_DATA_DIR}/data PATTERN ".svn" EXCLUDE PATTERN ".git" EXCLUDE)
endif()
#install(FILES ${LS_DATA_DIR}/laundredsheep.desktop DESTINATION share/applications)
#install(FILES data/laundredsheep_32.png DESTINATION share/icons/hicolor/32x32/apps RENAME laundredsheep.png)
#install(FILES data/laundredsheep_128.png DESTINATION share/icons/hicolor/128x128/apps RENAME laundredsheep.png)
#install(FILES data/laundredsheep_32.png data/laundredsheep_128.png DESTINATION share/pixmaps)
#install(FILES data/laundredsheep.appdata.xml DESTINATION share/appdata)

if(MINGW)
    install(DIRECTORY ${CMAKE_BINARY_DIR}/bin/ DESTINATION ${LS_INSTALL_BINARY_DIR}
            FILES_MATCHING PATTERN "*.dll")
endif()
